package com.spring.membercardapi.web.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;

import com.google.common.collect.Lists;
import com.spera.genutil.TokenUtil;
import com.spera.shopoa.util.ShopOaSessionUtil;
import com.spera.shopoa.util.ShopOaSessionUtil.OaUser;
import com.spring.cardapi.web.service.CardApiService;
import com.spring.common.web.dao.CommonApiMapper;
import com.spring.common.web.dao.ContractBabyMapper;
import com.spring.common.web.dao.ContractFileMapper;
import com.spring.common.web.dao.ContractsMapper;
import com.spring.common.web.dao.CrmContactMapper;
import com.spring.common.web.dao.CrmCustomerMapper;
import com.spring.common.web.dao.MembercardApplicationMapper;
import com.spring.common.web.dao.MembercardApplicationsPackagesMapper;
import com.spring.common.web.dao.MembercardMapper;
import com.spring.common.web.dao.RechargecardApplicationMapper;
import com.spring.common.web.dao.RechargecardMapper;
import com.spring.common.web.dao.TracelogboMapper;
import com.spring.common.web.model.Contract;
import com.spring.common.web.model.ContractBaby;
import com.spring.common.web.model.ContractFile;
import com.spring.common.web.model.CrmContact;
import com.spring.common.web.model.CrmCustomer;
import com.spring.common.web.model.Membercard;
import com.spring.common.web.model.MembercardApplication;
import com.spring.common.web.model.MembercardApplicationsPackages;
import com.spring.common.web.model.Rechargecard;
import com.spring.common.web.model.RechargecardApplication;
import com.spring.common.web.model.TracelogboWithBLOBs;
import com.spring.common.web.service.CommonService;
import com.spring.consumebackground.web.dao.ConsumeBackgroundMapper;
import com.spring.consumebackground.web.service.ConsumeBackgroundService;
import com.spring.membercardapi.web.dao.MemberCardApiMapper;
import com.spring.membercardapi.web.model.Application;
import com.spring.membercardapi.web.model.ApplicationB;
import com.spring.membercardapi.web.model.Card;
import com.spring.membercardapi.web.model.CardDetail;
import com.spring.membercardapi.web.model.Consume;
import com.spring.membercardapi.web.model.ContractUpdate;
import com.spring.membercardapi.web.model.DataDictionary;
import com.spring.membercardapi.web.model.MyCoupon;
import com.spring.membercardapi.web.model.OrderPayment;
import com.spring.membercardapi.web.model.PackageDetail;
import com.spring.membercardapi.web.model.PointBill;
import com.spring.membercardapi.web.requestmodel.ApplicationUpdate;
import com.spring.membercardapi.web.requestmodel.Guardians;
import com.spring.membercardapi.web.requestmodel.Packages;
import com.spring.membercardapi.web.service.MemberCardApiService;
import com.spring.rechargeapi.web.dao.RechargeApiMapper;
import com.spring.rechargeapi.web.service.RechargeApiService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.UpdateMap;
import com.spring.security.web.dao.CommonMapper;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;
import com.spring.tools.Result;
import com.spring.tools.ValidatorResultHandler;
import com.sso.api.web.dao.FamilyMapper;
import com.sso.api.web.dao.FamilyMemberMapper;
import com.sso.api.web.dao.SsoMapper;
import com.sso.api.web.model.FamilyMember;
import com.sso.api.web.model.RequestUser;
import com.sso.api.web.model.SsoFamily;
import com.sso.api.web.model.SsoFamilyUser;
import com.sso.api.web.model.SsoUser;
@Service
public class MemberCardApiServiceImpl implements MemberCardApiService{
	@Resource
	private MemberCardApiMapper memberCardApiMapper;
	
	@Resource
	private ConsumeBackgroundService consumeBackgroundService;
	
	@Resource
	private SsoMapper ssoMapper;
	
	@Resource
	private CardApiService cardApiService;
	
    @Resource
    private JedisCache jedisCache;
    
    @Resource
    private CommonMapper commonMapper;
        
	@Resource
	private ConsumeBackgroundMapper consumeBackgroundMapper;
    
	@Resource
	private CommonService commonService;
	
	@Resource
	private RechargeApiService rechargeApiService;
	
	@Resource
	private CommonApiMapper commonApiMapper;
	
	@Resource
	private CrmCustomerMapper crmCustomerMapper;
	
	@Resource
	private RechargeApiMapper rechargeApiMapper;	
	
	@Resource
	private FamilyMapper familyMapper;	
	
	@Resource
	private FamilyMemberMapper familyMemberMapper;	
	
	@Resource
	private ContractsMapper contractsMapper;	
	
	@Resource
	private CrmContactMapper crmContractsMapper;
	
	@Resource
	private ContractFileMapper contractFileMapper;	
	
	@Resource
	private MembercardMapper membercardMapper;	
	
	@Resource
	private RechargecardMapper rechargecardMapper;	

	@Resource
	private MembercardApplicationMapper membercardApplicationMapper;	
	
	@Resource
	private RechargecardApplicationMapper rechargecardApplicationMapper;
	
	@Resource
	private MembercardApplicationsPackagesMapper  membercardApplicationsPackagesMapper;	

	@Resource
	private ContractBabyMapper contractBabyMapper;	
	
	@Resource
	private TracelogboMapper tracelogboMapper;	
	
	//获取会员类型信息接口
	@Override
	public Map<String, Object> getCardTypeList() {
		Map<String, Object> m = new HashMap();
		try {
			List<HashMap> list = memberCardApiMapper.getCardTypeList();
			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "取数成功");
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}
		return m;
	}
	
	//获取套餐详细信息接口
	@Override
	public Map<String, Object> getPackageDetail(String package_id) {
		Map<String, Object> m = new HashMap();
		
		if(!ApplicationUtils.isNotNull(package_id)){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "package_id不能为空");
			return m;
		}
		
		try {
			
			List<PackageDetail> list = memberCardApiMapper
					.getPackageDetail(package_id);
			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "取数成功");

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}
		return m;
	}

	
	
	// 预约会员
	@Override
	public Map<String, Object> insertapplyCard(String token,String user_name, String family_member_id,String baby_name,
			String baby_sex_code,String baby_birthday,
			 String info_source_code,
			String card_level_code, String region_id, String coupon_code,
			String apply_way_code, String kids_park_id,String c_family_member_id ,String real_name , String guardians,String interest_service) throws Exception  {

			Map<String, Object> m = new HashMap();

			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {
				return t;
			}

			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			//验证参数
			if(!(ApplicationUtils.isNotNull(info_source_code)&&ApplicationUtils.isNotNull(card_level_code)
					&&ApplicationUtils.isNotNull(apply_way_code)&&ApplicationUtils.isNotNull(kids_park_id)
					&&ApplicationUtils.isNotNull(guardians)&&ApplicationUtils.isNotNull(baby_name)&&
					ApplicationUtils.isNotNull(baby_sex_code)&&ApplicationUtils.isNotNull(baby_birthday)
					&&ApplicationUtils.isNotNull(real_name)&&ApplicationUtils.isNotNull(c_family_member_id))){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入必要的参数");
				return m;
				
			}
			
			
			
			String uuid = ApplicationUtils.randomUUID();
			
			
			baby_birthday=MyTools.timestampToString(baby_birthday);
			
			
			//验证优惠码
			if(ApplicationUtils.isNotNull(coupon_code)){
			
			int count = memberCardApiMapper.applyCardCheckCoupon(coupon_code);

			if (count != 1) {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入有效的优惠码");
				return m;
				}
			
			
			
			HashMap applyCardUpdateCouponhm = new HashMap();
			applyCardUpdateCouponhm.put("c_user_id", c_user_id);
			applyCardUpdateCouponhm.put("coupon_code", coupon_code);
			applyCardUpdateCouponhm.put("user_name", real_name);

			int effect1 = memberCardApiMapper
					.applyCardUpdateCoupon(applyCardUpdateCouponhm);
			
			// 如果插入数不为一报错
			if (effect1 != 1) {
				System.out.println(effect1 + "插入出错");
				throw new Exception();
			}
		}

			System.out.println(guardians);


			//插入申请表
			HashMap hm = new HashMap();
			hm.put("uuid", uuid);
			hm.put("c_user_id", c_user_id);
			hm.put("family_member_id", family_member_id);
			hm.put("info_source_code", info_source_code);
			hm.put("card_level_code", card_level_code);
			hm.put("region_id", region_id);
			hm.put("coupon_code", coupon_code);
			hm.put("apply_way_code", apply_way_code);
			hm.put("kids_park_id", kids_park_id);
			hm.put("baby_name", baby_name);
			hm.put("baby_sex_code", baby_sex_code);
			hm.put("baby_birthday", baby_birthday);
			
			hm.put("baby_id", c_family_member_id);
			hm.put("real_name", real_name);
			hm.put("interest_service", interest_service);
			
			
			System.out.println(hm.toString());
			
			int effect = memberCardApiMapper.applyCard(hm);

			if (effect != 1) {
				System.out.println(effect + "插入出错");
				throw new Exception();
			}
			

			JSONArray json = JSONArray.fromObject(guardians);
			// 循环插入监护人
			if(json.size()<1){
				throw new Exception();
			}
			
			for (int i = 0; i < json.size(); i++) {
				JSONObject jsonObject = json.getJSONObject(i);

				System.out.println(jsonObject.get("family_member_id"));

				String parent_id = (String) jsonObject.get("family_member_id");
				String identity_card = (String) jsonObject.get("identity_card");
				String name = (String) jsonObject.get("name");
				String phone = (String) jsonObject.get("phone");
				String member_name = (String) jsonObject.get("name");
			
				
				HashMap hmc=MyTools.checkIsNotNull(identity_card,name,phone,member_name);
				if(hmc!=null){
					throw new Exception();
				}
				
				
				HashMap hm2 = new HashMap();
				hm2.put("uuid", uuid);
				hm2.put("family_member_id", parent_id);
				hm2.put("identity_card", identity_card);
				hm2.put("name", name);
				hm2.put("phone", phone);
				hm2.put("member_name", member_name);

				int effect2 = memberCardApiMapper.applyCardInsertGuardian(hm2);

				System.out.println("循环插入监护人effect2" + effect2);

				// 如果插入数不为一报错
				if (effect2 != 1) {
					System.out.println(effect + "插入出错");
					throw new Exception();
				}

			}
			
			

			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "插入成功");


		return m;

	}
	
	
	

	
	//获取数字字典
	@Override
	public Map<String, Object> getDataDictionaryList(String type) {
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();
		
		
		try {
			
			if(!ApplicationUtils.isNotNull(type)){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入类型");	
				return m;
			}
			
			List<DataDictionary> list = memberCardApiMapper.getDataDictionaryList(type);
			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "取数成功");

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}
		return m;
	}

	/**
	 * 查看入会申请
	 */
	@Override
	public Map<String, Object> getApplicationList(String token,String application_id) {
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();
		
		try {
			
			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {
				return t;
			}

			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			HashMap hm=new HashMap();
			hm.put("c_user_id", c_user_id);
			hm.put("application_id", application_id);
			
			
			List<Application> list = memberCardApiMapper.getApplicationList(hm);
			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "取数成功");

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
			
		}
		return m;
	}
	
	
	/**
	 * 修改预约会员申请
	 */
	
	@Override
	public Map<String, Object> updateApplication (String token,
			String application_id, String baby_name,String baby_sex_code,String baby_birthday,
			String info_source_code, String card_level_code, String region_id,
			String coupon_code, String kids_park_id) throws Exception{
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();
		
			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {
				return t;
			}

			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			if(ApplicationUtils.isNotNull(baby_birthday)){
				baby_birthday=MyTools.timestampToString(baby_birthday);
			}
			
			
			//验证申请id是否可用
			int effect = memberCardApiMapper.updateApplicationCheckID(application_id);
			if(effect!=1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入可以修改的申请id");
				return m;
			}
			
			//验证优惠码
			if(ApplicationUtils.isNotNull(coupon_code)){
				
				int count = memberCardApiMapper.applyCardCheckCoupon(coupon_code);

				if (count != 1) {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "请输入有效的优惠码");
					return m;
					}
				
			//标记优惠码为已用
			HashMap applyCardUpdateCouponhm = new HashMap();
			applyCardUpdateCouponhm.put("c_user_id", c_user_id);
			applyCardUpdateCouponhm.put("coupon_code", coupon_code);

			int effect2 = memberCardApiMapper
					.applyCardUpdateCoupon(applyCardUpdateCouponhm);
			}
			
			HashMap hm2=new HashMap();
			
			//修改申请表数据
			
			hm2.put("application_id", application_id);
			//hm2.put("family_member_id", family_member_id);
			hm2.put("info_source_code", info_source_code);
			hm2.put("card_level_code", card_level_code);
			hm2.put("region_id", region_id);
			hm2.put("coupon_code", coupon_code);
			hm2.put("kids_park_id", kids_park_id);
			hm2.put("baby_name", baby_name);
			hm2.put("baby_sex_code", baby_sex_code);
			hm2.put("baby_birthday", baby_birthday);
			
			
			int effect3 = memberCardApiMapper.updateApplication(hm2);
			
			if(effect3!=1){
			//	throw new Exception();
			}
			
			//List<Application> list = memberCardApiMapper.getApplicationList(c_user_id);
			//m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "取数成功");
	
		
		return m;
	}
	
	
	
	/**
	 * 修改预约会员申请监护人信息
	 */
	@Override
	public Map<String, Object> updateGuardian (String token,String guardian_id,String family_member_id,
			String identity_card,String name,String phone,String member_name) throws Exception{
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();
		
			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {
				return t;
			}
			
			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			//
			HashMap hm=new HashMap();
			hm.put("guardian_id", guardian_id);
			hm.put("family_member_id", family_member_id);
			hm.put("identity_card", identity_card);
			hm.put("name", name);
			hm.put("phone", phone);
			hm.put("member_name", member_name);
			
			
			int effect=memberCardApiMapper.updateGuardian(hm);
			
			if(effect!=1){
					throw new Exception();
				}
			
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "添加成功");
	
		
		return m;
	}
	
	/**
	 * 删除预约会员申请监护人信息
	 */
	@Override
	public Map<String, Object> deleteGuardian(String token,String guardian_id) throws Exception{
		Map<String, Object> m = new HashMap();
		
		
		Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
		if (t != null) {
			return t;
		}
		
		HashMap hmc=MyTools.checkIsNotNull(guardian_id);
		if(hmc!=null){
			return hmc;
		}
		
//		String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
		
		
		HashMap hm=new HashMap();
		hm.put("guardian_id", guardian_id);

		int effect=memberCardApiMapper.deleteGuardian(guardian_id);
		
		if(effect!=1){
				throw new Exception();
			}
		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "删除成功");

	
	return m;
	}
	
	
	/**
	 * 添加预约会员申请监护人信息
	 */
	@Override
	public Map<String, Object> addApplicationGuardian (String token,String membercard_application_id,String family_member_id,
			String identity_card,String name,String phone,String member_name) throws Exception{
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();
		
		
			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {
				return t;
			}

//			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			
			HashMap hmc=MyTools.checkIsNotNull(membercard_application_id,identity_card,name,phone,member_name);
			if(hmc!=null){
				return hmc;
			}
			
			//验证membercard_application_id的有效性
			int effect2= memberCardApiMapper.addApplicationGuardianCheckApplicationID(membercard_application_id);
			
			if(effect2!=1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入有效的membercard_application_id");
				return m;
			}
			
			
			//验证是否重复添加家庭成员
			HashMap hm2=new HashMap();
			hm2.put("membercard_application_id", membercard_application_id);
			hm2.put("family_member_id", family_member_id);
			int effect1=memberCardApiMapper.addApplicationGuardianCheckID(hm2);
			
			if(effect1>=1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "不能重复添加家庭成员");
				return m;
			}
			
			HashMap hm=new HashMap();
			
			hm.put("membercard_application_id", membercard_application_id);
			hm.put("family_member_id", family_member_id);
			hm.put("identity_card", identity_card);
			hm.put("name", name);
			hm.put("phone", phone);
			hm.put("member_name", member_name);
			
			int effect=memberCardApiMapper.addApplicationGuardian(hm);
			
			
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "修改成功");
	
		
		return m;
	}
	
	
	/**
	 * 取消预约会员申请
	 */
	@Override
	public Map<String, Object> cancelApplication (String token,String membercard_application_id,String cancel_reason) throws Exception{
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();
		
		
			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {
				return t;
			}

			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			//验证membercard_application_id的有效性
			int effect= memberCardApiMapper.cancelApplicationCheceApplicationId(membercard_application_id);
			
			
			if(effect!=1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入可以取消的membercard_application_id");
				return m;
			}
			
			
			//删除监护人
			int effect1= memberCardApiMapper.cancelApplicationDeleteGuardian(membercard_application_id);
			
			//删除监护人申请
			HashMap hm=new HashMap();
			hm.put("membercard_application_id", membercard_application_id);
			hm.put("cancel_reason", cancel_reason);
			
			int effect2= memberCardApiMapper.cancelApplication(hm);
			
			
			
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "删除成功");
	
		
		return m;
	}
	
	
	
	/**
	 * 查看自己有的会员卡
	 */
	@Override
	public Map<String, Object> getCardList (String token,String isvalid) throws Exception{
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();
		
		
			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {
				return t;
			}

			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			HashMap hm=new HashMap();
			hm.put("c_user_id", c_user_id);
			hm.put("isvalid", isvalid);
			
			
			
			List<Card> list= memberCardApiMapper.getCardList(hm);
			
			
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");
			m.put(ApplicationUtils.DATASET, list);
	
		
		return m;
	}
	
	
	
	
	@Override
	public Map<String, Object> getCardDetaiList(String token,
			String membercard_id) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
		if (t != null) {
			return t;
		}

		String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
		
		if (!ApplicationUtils.isNotNull(membercard_id)
				) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入必要的参数");
			return m;
		}
		
		HashMap hm = new HashMap();

		hm.put("membercard_id", membercard_id);

		List<CardDetail> list = memberCardApiMapper
				.getCardDetaiList(membercard_id);

		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "查询成功");
		m.put(ApplicationUtils.DATASET, list);

		return m;
	}
	
	
	
	/**
	 * 会员消费登记
	 */
	@Override
	public Map<String, Object> checkOut(String token, String membercard_id,
			String business_type_code,String package_detail_item_id, String amount, String comment,
			String unit_code, String payment_way_code,String kids_park_id) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
		if (t != null) {
			return t;
		}

		String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);

		
		if (!(ApplicationUtils.isNotNull(membercard_id)
				&& ApplicationUtils.isNotNull(business_type_code)
				&& ApplicationUtils.isNotNull(amount)
				&& ApplicationUtils.isNotNull(package_detail_item_id) 
				&& ApplicationUtils.isNotNull(unit_code) 
				
				&& ApplicationUtils
					.isNotNull(payment_way_code)&&ApplicationUtils.isNotNull(kids_park_id))) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入必要的参数");
			return m;
		}
		
		

		int count = memberCardApiMapper.checkOutCheckCard(membercard_id);

		
		if(count!=1){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "输入的卡无效");
			return m;
		}
		
		
		HashMap hm = new HashMap();
		hm.put("membercard_id", membercard_id);
		hm.put("business_type_code", business_type_code);
		hm.put("package_detail_item_id", package_detail_item_id);
		
		
		
		BigDecimal remainQuantity=memberCardApiMapper.checkOutRemainQuantity(hm);
		
		if(remainQuantity.compareTo(new BigDecimal(amount))==-1){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "余额不足");
			return m;
		}
		
		HashMap hm2 = new HashMap();
		hm2.put("amount", amount);
		hm2.put("business_type_code", business_type_code);
		hm2.put("membercard_id", membercard_id);
		hm2.put("package_detail_item_id", package_detail_item_id);
		
		
		int effect=memberCardApiMapper.checkOutUpdateRemainQuantity(hm2);
		
		if(effect!=1){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "付款失败");
			return m;
		}
		
		
		String uuid=ApplicationUtils.randomUUID();
		
		HashMap hm3 = new HashMap();
		hm3.put("uuid", uuid);
		hm3.put("business_type_code", business_type_code);
		hm3.put("amount", amount);
		hm3.put("payment_way_code", payment_way_code);
		hm3.put("c_user_id", c_user_id);
		hm3.put("membercard_id", membercard_id);
		hm3.put("kids_park_id", kids_park_id);
		hm3.put("comment", comment);
		hm3.put("package_detail_item_id", package_detail_item_id);
		hm3.put("unit_code", unit_code);
		
		
		
		
		int effect2=memberCardApiMapper.checkOutInsertConsumeHis(hm3);
		
		if(effect2!=1){
			throw new Exception();
		}
		
		
		/*	HashMap hm4 = new HashMap();
		hm4.put("uuid", uuid);
		hm4.put("business_type_code", business_type_code);
		hm4.put("membercard_id", membercard_id);
		
		
		int effect3=memberCardApiMapper.checkOutInsertJournalAccount(hm4);
		
		if(effect3!=1){
			throw new Exception();
		}
		*/
		
		
		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "付款成功");
		//m.put(ApplicationUtils.DATASET, list);

		return m;
	}
	
	

	/**
	 * 查看自己消费记录
	 */
	@Override
	public Map<String, Object> getConsumeList(String token,String membercard_id,String page_size,
			String page_index,String skip,String rows) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
		if (t != null) {
			return t;
		}
		
		
		if(!ApplicationUtils.isNotNull(membercard_id)){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入membercard_id");
			return m;
		}
		

		String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);

		
		int pagesize=20;
		int pageindex=1;
		int skipint=0;
		int rowsint=20;
		
		if(page_size!=null&&page_index!=null){
			
			 pagesize=Integer.parseInt(page_size);
			 pageindex=Integer.parseInt(page_index);
			
			skipint=pagesize*(pageindex-1);
			rowsint=pagesize;
			
		}else if(skip!=null&&rows!=null){
			
			 skipint=Integer.parseInt(skip);
			 rowsint=Integer.parseInt(rows);
			
		}
		
		
		HashMap hm = new HashMap();
		hm.put("membercard_id", membercard_id);
		hm.put("skip", skipint);
		hm.put("rows", rowsint);
		
		
	//	PageHelper.startPage(Integer.parseInt(page_index),
	//			Integer.parseInt(page_size));
		List<Consume> list = memberCardApiMapper.getConsumeList(hm);
				

		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "查询成功");
		m.put(ApplicationUtils.DATASET, list);

		return m;
	}
	
	
	
	
	
	
	
	
	/**
	 * 查看自己积分流水记录
	 */
	@Override
	public Map<String, Object> getPointBillList(String token,String page_size,
			String page_index,String skip,String rows) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
		if (t != null) {
			return t;
		}

		String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);

		
		int pagesize=20;
		int pageindex=1;
		int skipint=0;
		int rowsint=20;
		
		if(page_size!=null&&page_index!=null){
			
			 pagesize=Integer.parseInt(page_size);
			 pageindex=Integer.parseInt(page_index);
			
			skipint=pagesize*(pageindex-1);
			rowsint=pagesize;
			
		}else if(skip!=null&&rows!=null){
			
			 skipint=Integer.parseInt(skip);
			 rowsint=Integer.parseInt(rows);
			
		}
		
		HashMap hm = new HashMap();
		hm.put("c_user_id", c_user_id);
		hm.put("skip", skipint);
		hm.put("rows", rowsint);
		List<PointBill> list = memberCardApiMapper.getPointBillList(hm);
				

		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "查询成功");
		m.put(ApplicationUtils.DATASET, list);

		return m;
	}
	
	/**
	 * 产生优惠码
	 */
	@Override
	public Map<String, Object> createCouponCode(String token) throws Exception{
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
		if (t != null) {
			return t;
		}

		String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
		
		int code=(int)(Math.random()*100000);
		
		HashMap hm = new HashMap();
		hm.put("c_user_id", c_user_id);
		hm.put("code", code);
		
		int effect = memberCardApiMapper.createCouponCode(hm);
		
		if(effect!=1){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "插入失败");
			return m;
		}
		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "插入成功");
		
		
		return m;
	}
	
	
	
	/**
	 * 查看自己的优惠码
	 */
	@Override
	public Map<String, Object> getMyCouponList(String token,String isused) throws Exception{
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
		if (t != null) {
			return t;
		}

		String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
		

		
		HashMap hm = new HashMap();
		hm.put("c_user_id", c_user_id);
		hm.put("isused", isused);
		
		List<MyCoupon> list = memberCardApiMapper.getMyCouponList(hm);
		
		
		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "插入成功");
		m.put(ApplicationUtils.DATASET, list);
		
		return m;
	}
	
	@Override
	public Map<String, Object> applyCardBackground2(String real_name, String phone, 
			String info_source_code, String coupon_code, String apply_way_code,
			String kids_park_id, String interest_service, String assistant_id, 
			String assistant_name, String auditor_id, 
			String auditor_name, String desc,String operater_id, String operater_name, 
			String consume_recommend_id,
			String consume_recommend_name, List<Map<String,Object>> guardians,
			List<Map<String,Object>> baby,List<Map<String,Object>> packages,
			String address,String zipcode,String apply_type,String family_phone,String consume_recommend_deptID
			,String consume_recommend_dept_name,String InitialOperatorID,String InitialOperatorName,
			
			String earnestMoney,
			String order_payment2,String payment_amount,
			String card_number,String card_out_number,String contract_name,String begin_time,String end_time,String file,
			
			String rechargeCardCategory,String recharge_amount,String point,String totalDueAmount,
			String isDiscount,String discount_type,
			HttpServletRequest request) throws Exception  {
		
			if(rechargeCardCategory==null){
				rechargeCardCategory="1";
			}
			if(recharge_amount==null){
				recharge_amount="0";
			}
			if(point==null){
				point="0";
			}

			Map<String, Object> resultt=new HashMap<String,Object>();
			
			int hasPackage=0;
			String contractID=null;
			String orderID=null;
			
			Map<String, Object> f=checkParameter(card_number,card_out_number);
			String statusf=MyTools.ObjectToString(f.get("status"));

			if(statusf.equals("0")){
				return f;
			}
			
			//if(packages!=null&&packages.size()>0){
		//		hasPackage=1;
				Map<String, Object>  result=applyCardBackground( real_name,  phone,  info_source_code,  coupon_code,  apply_way_code,
						 kids_park_id,  interest_service,  assistant_id,  assistant_name,  auditor_id, 
						 auditor_name,  desc, operater_id,  operater_name,  consume_recommend_id,
						 consume_recommend_name,  guardians,baby,packages,
						 address, zipcode, apply_type, family_phone, consume_recommend_deptID
						, consume_recommend_dept_name, InitialOperatorID, InitialOperatorName, null, earnestMoney,request);
				
				String status=MyTools.ObjectToString(result.get("status"));

				if(status.equals("1")){
					
					Map<String,Object> dataset=(Map<String,Object>)result.get("dataset");
					String applicationID = MyTools.ObjectToString(dataset.get("applicationID"));	
										
					resultt=applyCardPayment(order_payment2, applicationID, payment_amount,
							 card_number, card_out_number, contract_name, begin_time, end_time, file, InitialOperatorID, 
							 InitialOperatorName,recharge_amount,totalDueAmount,earnestMoney,operater_id,operater_name,isDiscount,
							 kids_park_id,request);					
					
					if(MyTools.ObjectToString(resultt.get("status")).equals("0")){
						System.out.println(resultt.get("msg"));
						throw new Exception();
					}
					
				}else{
					return result;
				}	
		//	}
			
			//if(hasPackage==1){
				apply_type="2";
				contractID=MyTools.ObjectToString(resultt.get("contractID")) ;
				
				BigDecimal useAmount=(BigDecimal)resultt.get("useAmount");
				
				System.out.println(contractID);
				orderID=MyTools.ObjectToString(resultt.get("orderID"));
				card_number=null;
				card_out_number=null;
		//	}
			
			if(StringUtils.isNoneBlank(recharge_amount)){
				
				Map<String, Object>  result2=rechargeApiService.applyCardBackground(point, rechargeCardCategory, phone, 
						family_phone, address, zipcode, recharge_amount, apply_way_code, 
						auditor_id, auditor_name, desc, operater_id, operater_name, 
						consume_recommend_id, consume_recommend_name, kids_park_id, 
						baby, guardians, apply_type, consume_recommend_deptID, 
						consume_recommend_dept_name, InitialOperatorID, InitialOperatorName, 
						earnestMoney,discount_type, request);
				
				String status2=MyTools.ObjectToString(result2.get("status"));

				if(status2.equals("1")){
					Map<String,Object> dataset=(Map<String,Object>)result2.get("dataset");
					String applicationID = MyTools.ObjectToString(dataset.get("applicationID"));
					
					Map<String, Object> result23=rechargeApiService.applyCardPayment(applicationID,
							payment_amount, card_number, card_out_number, contract_name, 
							begin_time, end_time, file, InitialOperatorID, InitialOperatorName,
							hasPackage, contractID, orderID,totalDueAmount,earnestMoney,discount_type);
					
					HashMap datasets = new HashMap();
					
					int EntityAvailableState=10;
					
					if (earnestMoney!=null&&!earnestMoney.equals("0")){
						EntityAvailableState=2;
					}
					
					datasets.put("EntityAvailableState", EntityAvailableState);
					datasets.put("useAmount", useAmount);
					datasets.put("contractID", contractID);
					
					result23.put("dataset", datasets);
					
					return result23;
				}else{
					throw new Exception();
				}	
			}else{
				return resultt;
			}
	}

	// 预约会员后台调用
		@Override
		public Map<String, Object> applyCardBackground(String real_name, String phone, String info_source_code, String coupon_code, String apply_way_code,
				String kids_park_id, String interest_service, String assistant_id, String assistant_name, String auditor_id, 
				String auditor_name, String desc,String operater_id, String operater_name, String consume_recommend_id,
				String consume_recommend_name, List<Map<String,Object>> guardians,List<Map<String,Object>> baby,List<Map<String,Object>> packages,
				String address,String zipcode,String apply_type,String family_phone,String consume_recommend_deptID
				,String consume_recommend_dept_name,String InitialOperatorID,String InitialOperatorName,String applicationID,String earnestMoney,HttpServletRequest request) throws Exception  {
				
				Map<String, Object> m = new HashMap();

				OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
				if(oaUser==null){
					
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "请先登录");
					return m;		
				}
				
				InitialOperatorID=oaUser.getOa_user_id();
				InitialOperatorName=oaUser.getOa_user_name();
				
				if(earnestMoney==null){
					earnestMoney="0";
				}
			
				if(applicationID==null||applicationID.equals("")){

				
				Map<String, Object> ContractMap = new HashMap();
				
				//验证参数				
				HashMap hmc=MyTools.checkIsNotNull(phone,info_source_code,
						apply_way_code,kids_park_id,
						apply_type);
				if(hmc!=null){
					return hmc;
				}
				
				if(coupon_code!=null&&coupon_code.equals("null")){
					coupon_code=null;
				}
				BigDecimal total_amount=new BigDecimal(0);
				String[] packagestr=null;
				//验证套餐参数
				if(packages!=null){
					 packagestr=new String[packages.size()] ;
					for(int i=0;i<packages.size();i++){
						Map<String,Object> jsonObject2 =(Map<String,Object>)packages.get(i);

						String packageID =MyTools.ObjectToString(jsonObject2.get("id"));
						String real_price = MyTools.ObjectToString(jsonObject2.get("real_price")) ;	
						HashMap hmcc4=MyTools.checkIsNotNull(packageID,real_price);
						if(hmcc4!=null){
							return hmcc4;
						}
						packagestr[i]=packageID;
						
						total_amount=total_amount.add(new BigDecimal(real_price));
						
					}
				}	
/*				if(total_amount.compareTo(new BigDecimal(earnestMoney))==-1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "定金不能大于总金额");
					return m;															
				}*/
				
				System.out.println(total_amount);
				
				String c_familyID=null;
				String c_user_id=null;
				List<Map<String,Object>> blist = Lists.newArrayList();
				//注册用户
				if(apply_type.equals("1")){
				
			if (baby != null) {

				// 验证宝宝参数
				for (int i = 0; i < baby.size(); i++) {
					Map<String, Object> jsonObject2 = (Map<String, Object>) baby
							.get(i);

					String baby_name2 = String.valueOf(jsonObject2.get("name"));
					String baby_sex_code2 = String.valueOf(jsonObject2.get("sex_code"));
					String baby_birthday2 = String.valueOf(jsonObject2.get("birthday"));
					String memeber_name = String.valueOf(jsonObject2.get("member_name"));

					HashMap hmcc2 = MyTools.checkIsNotNull(baby_name2,
							baby_birthday2, baby_sex_code2, memeber_name);
					if (hmcc2 != null) {
						return hmcc2;
					}

				}

			}
		
				RequestUser ru=new RequestUser();
				ru.setPhone(phone);
				
				boolean temp=false;
				
				CrmCustomer crmCustomer=new CrmCustomer();	
				
				CrmContact crmContact=new CrmContact();	
				
				for(Map<String,Object> jsonObject:guardians){
	
					String phone3 = (String) jsonObject.get("phone");
					String identity_card = (String) jsonObject.get("identity_card");
					String name = (String) jsonObject.get("name");					
					String member_name = (String) jsonObject.get("member_name");
					String role_id = (String) jsonObject.get("role_id");
					String email = (String) jsonObject.get("email");
					String companyName = (String) jsonObject.get("companyName");
					
					if(phone3.equals(phone)){
						temp=true;
						
						real_name=name;
						
						ru.setIdentity_card(identity_card);
						ru.setReal_name(name);
						ru.setMember_name(member_name);
						ru.setC_role_id(role_id);
						ru.setUserName(phone);
						ru.setAddress(address);
						ru.setEmail(email);
						ru.setCompanyName(companyName);
						ru.setAdmission_way_id("1");
						ru.setKids_parkID(kids_park_id);
						
						crmCustomer.setCustomername(name);
						crmCustomer.setKidsParkid(kids_park_id);
						crmCustomer.setInitialoperatorid(InitialOperatorID);
						crmCustomer.setInitialoperatorname(InitialOperatorName);
						crmCustomer.setRecommenderid(consume_recommend_id);
						crmCustomer.setRecommendername(consume_recommend_name);
						crmCustomer.setRecommenderdeptid(consume_recommend_deptID);
						crmCustomer.setRecommenderdeptname(consume_recommend_dept_name);
						crmCustomer.setDesc(desc);
						crmCustomer.setBusinessTypesid("8b8263f1-02c8-44ba-a398-bd31b3bb72a4");
						crmCustomer.setResponserdeptid(oaUser.getUser_dept_id());
						crmCustomer.setResponserdeptname(oaUser.getUser_dept_name());
						
						crmContact.setName(name);
						crmContact.setPhonenumber(phone3);
						crmContact.setEmail(email);
						crmContact.setIsmaincontact(1);
						crmContact.setCompanyname(companyName);
						crmContact.setCertificatenumber(identity_card);
						crmContact.setRoleid(role_id);
						crmContact.setDesc(desc);
						crmContact.setInitialoperatorid(InitialOperatorID);
						crmContact.setInitialoperatorname(InitialOperatorName);
					}
					
					
					HashMap hmcc=MyTools.checkIsNotNull(name,member_name,role_id);
					if(hmcc!=null){
						return hmcc;
					}
								
				};
				
				//验证主手机号是否
				if(temp==false){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "合同手机号必须是监护人手机号之一");
					return m;
				}
			
			//	String address,String zipcode
				
				ru.setFamily_address(address);
				ru.setZipcode(zipcode);
				ru.setFamily_phone(family_phone);
				
				crmContact.setHomephone(family_phone);
				crmContact.setPostcode(zipcode);
				
				
				//发起请求用于注册主账号
				Map<String, Object> hm=cardApiService.addUser(ru,request);
				
				if(!hm.get(ApplicationUtils.STATUS).equals("1")){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, hm.get(ApplicationUtils.MSG));
					return m;
				}

				HashMap<String,Object>  hm2=(HashMap<String,Object>)hm.get(ApplicationUtils.DATASET);
				 c_familyID=String.valueOf(hm2.get("c_familyID"));
				 c_user_id=String.valueOf(hm2.get("c_user_id"));
				 
				 crmContact.setCuserid(c_user_id);
				 
				 crmCustomer.getCrmContact().add(crmContact);
				 
				//注册其他监护人账号
				for(Map<String,Object> jsonObject:guardians){
				//	JSONObject jsonObject = json2.getJSONObject(i);
					RequestUser ru1=new RequestUser();
					
					String phone3 = (String) jsonObject.get("phone");
					if(!phone3.equals(phone)){
						
						String identity_card = (String) jsonObject.get("identity_card");
						String name = (String) jsonObject.get("name");					
						String member_name = (String) jsonObject.get("member_name");
						String role_id = (String) jsonObject.get("role_id");
						String email = (String) jsonObject.get("email");
						String companyName = (String) jsonObject.get("companyName");
						
						ru1.setC_family_id(c_familyID);												
						ru1.setIdentity_card(identity_card);
						ru1.setReal_name(name);											
						ru1.setMember_name(member_name);
						ru1.setC_role_id(role_id);						
						ru1.setUserName(phone);
						ru1.setEmail(email);
						ru1.setCompanyName(companyName);
						ru1.setAdmission_way_id("1");
						ru1.setKids_parkID(kids_park_id);
						
						Map<String, Object> hm3=cardApiService.addUser(ru1,request);						
						if(!hm3.get(ApplicationUtils.STATUS).equals("1")){
							throw new Exception();
						}
						HashMap<String,Object>  hm4=(HashMap<String,Object>)hm3.get(ApplicationUtils.DATASET);
						 c_familyID=String.valueOf(hm4.get("c_familyID"));
						 c_user_id=String.valueOf(hm4.get("c_user_id"));
						
						 	
						crmContact.setName(name);
						crmContact.setPhonenumber(phone3);
						crmContact.setEmail(email);
						crmContact.setIsmaincontact(0);
						crmContact.setCompanyname(companyName);
						crmContact.setCertificatenumber(identity_card);
						crmContact.setRoleid(role_id);
						crmContact.setDesc(desc);
						crmContact.setInitialoperatorid(InitialOperatorID);
						crmContact.setInitialoperatorname(InitialOperatorName);
						crmContact.setHomephone(family_phone);
						crmContact.setPostcode(zipcode);
						crmContact.setCuserid(c_user_id);
						 
						crmCustomer.getCrmContact().add(crmContact);
					}
				}
				commonService.addCustomer(crmCustomer);
				
				//注册宝宝账号
				if (baby != null) {
					
				for(Map<String,Object> jsonObject:baby){
					//	JSONObject jsonObject = json2.getJSONObject(i);
					if(!ApplicationUtils.isNotNull(ApplicationUtils.Object2String(jsonObject.get("c_user_id")))){
						RequestUser ru1=new RequestUser();
						String baby_name = String.valueOf(jsonObject.get("name"));
						String baby_sex_code = String.valueOf(jsonObject.get("sex_code")) ;					
						String baby_birthday = String.valueOf(jsonObject.get("birthday"));
						String member_name = String.valueOf(jsonObject.get("member_name"));
						ru1.setC_family_id(c_familyID);							
						ru1.setReal_name(baby_name);
						ru1.setUserName(ApplicationUtils.randomUUID());
						ru1.setMember_name(member_name);
						ru1.setSex_code(baby_sex_code);
						ru1.setBirthday(baby_birthday);
						ru1.setC_role_id("0");
						ru1.setAdmission_way_id("1");
						ru1.setKids_parkID(kids_park_id);
						
						Map<String, Object> hm3=cardApiService.addUser(ru1,request);

						if(!hm3.get(ApplicationUtils.STATUS).equals("1")){
								throw new Exception();
						}
						//System.out.println(((HashMap<String,Object>)hm3.get(ApplicationUtils.DATASET)).get("c_user_id"));
						jsonObject.put("c_user_id", ((HashMap<String,Object>)hm3.get(ApplicationUtils.DATASET)).get("c_user_id"));
					}
					blist.add(jsonObject);
				}
			}		
				
		}else if(apply_type.equals("2")){
			HashMap hm=new HashMap();
			hm.put("phone", phone);
			hm.put("isAll",1);
			List<HashMap> list= ssoMapper.getIDsByPhone(hm);
			if(list.size()<1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "使用该手机注册的家庭不存在");
				return m;
			}
			
			
			HashMap hp=new HashMap();
			hp.put("c_family_id", list.get(0).get("c_family_id"));
			hp.put("family_phone",family_phone );
			hp.put("address",address);
			hp.put("zipcode",zipcode);
			

		//	c_family_id
		//	int effectn=ssoMapper.updateFamily(hp);

			
			HashMap hmr=list.get(0);
			//c_user_id=ssoFamily.g
			c_familyID=String.valueOf(hmr.get("c_family_id"));
			c_user_id=String.valueOf(hmr.get("c_user_id"));
			real_name=String.valueOf(hmr.get("real_name"));
		}else{
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入有效的apply_type");
			return m;
			
		}

			String uuid = ApplicationUtils.randomUUID();		
		//	baby_birthday=MyTools.timestampToString(baby_birthday);				
			
			//验证优惠码
			if(ApplicationUtils.isNotNull(coupon_code)){
				int count = memberCardApiMapper.applyCardCheckCoupon(coupon_code);
				if (count != 1) {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "请输入有效的优惠码");
					return m;
				}
				
				HashMap applyCardUpdateCouponhm = new HashMap();
				applyCardUpdateCouponhm.put("c_user_id", c_user_id);
				applyCardUpdateCouponhm.put("coupon_code", coupon_code);
				applyCardUpdateCouponhm.put("user_name", real_name);
	
				int effect1 = memberCardApiMapper
						.applyCardUpdateCoupon(applyCardUpdateCouponhm);
				
				// 如果插入数不为一报错
				if (effect1 != 1) {
					System.out.println(effect1 + "插入出错");
					throw new Exception();
				}
			}
			
			//System.out.println(guardians);

			//插入申请表
			HashMap hm3 = new HashMap();
			hm3.put("uuid", uuid);
			hm3.put("c_user_id", c_user_id);
			hm3.put("user_name", real_name);
			
			hm3.put("info_source_code", info_source_code);
//				hm3.put("card_level_code", card_level_code);
			hm3.put("coupon_code", coupon_code);
			hm3.put("apply_way_code", apply_way_code);
			hm3.put("kids_park_id", kids_park_id);

			hm3.put("real_name", real_name);
			hm3.put("interest_service", interest_service);
			hm3.put("auditor_name", auditor_name);
			hm3.put("desc", desc);
			hm3.put("operater_id", operater_id);
			hm3.put("operater_name", operater_name);
			hm3.put("consume_recommend_id", consume_recommend_id);
			hm3.put("consume_recommend_name", consume_recommend_name);
			hm3.put("phone", phone);
			hm3.put("c_family_id", c_familyID);
			
			hm3.put("consume_recommend_deptID", consume_recommend_deptID);
			hm3.put("consume_recommend_dept_name", consume_recommend_dept_name);
			
			hm3.put("InitialOperatorID", InitialOperatorID);
			hm3.put("InitialOperatorName", InitialOperatorName);
			
			hm3.put("earnestMoney", earnestMoney);
			
			
			HashMap hm6=new HashMap();
			hm6.put("package", packagestr);	
			BigDecimal packagePrice=new BigDecimal(0);
			if(packagestr!=null&&packagestr.length>0){
				packagePrice=memberCardApiMapper.getPackagePrice(hm6);	
			}
			
			hm3.put("origin_price", packagePrice);
			
			hm3.put("price", total_amount);
			if(coupon_code!=null&&!coupon_code.equals("")){
				BigDecimal codeAmount=memberCardApiMapper.getCouponCodeAmount(hm3);					
				hm3.put("codeAmount", codeAmount);	
			}
			
//				System.out.println(hm.toString());
			
			int effect = memberCardApiMapper.applyCardBackground(hm3);

			if (effect != 1) {
//					System.out.println(effect + "插入出错");
				throw new Exception();
			}
			
			//插入套餐关联关系		
			if(packages!=null){
			for(int i=0;i<packages.size();i++){
				Map<String,Object> jsonObject3 =(Map<String,Object>)packages.get(i);
				String packageID =MyTools.ObjectToString(jsonObject3.get("id")) ;	
				String real_price =MyTools.ObjectToString(jsonObject3.get("real_price")) ;
				String reason=MyTools.ObjectToString(jsonObject3.get("reason")) ;
				
				HashMap r=MyTools.checkIsNotNull(packageID,real_price);
				if(r!=null){
					return r;
				}
				
				HashMap hm7=new HashMap();
				hm7.put("c_membercard_applicationID", uuid);
				hm7.put("packageID", packageID);
				hm7.put("real_price", real_price);
				hm7.put("reason", reason);
				int effect3=memberCardApiMapper.insertApplicationPackage(hm7);
				if(effect3!=1){
					throw new Exception();
				}
			}	
			}
			HashMap<String,Object> hmx=new HashMap<String,Object>();
			hmx.put("applicationID", uuid);
			
			//插入合同宝宝关联表
			for(Map<String,Object> jsonObject:blist){
				jsonObject.put("applicationID", uuid);
				jsonObject.put("InitialOperatorID", InitialOperatorID);
				jsonObject.put("InitialOperatorName", InitialOperatorName);
				memberCardApiMapper.insertContractBabys(jsonObject);
			}
			
			m.put(ApplicationUtils.DATASET, hmx);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "申请成功");
		} else {
			//更新申请			
		}								
			return m;				
		}
	
		@Override
		public Object updateapply(ApplicationUpdate application,BindingResult result,HttpServletRequest request) throws Exception  {
				
				Map<String, Object> m = new HashMap();	

				Map<String, Object> ContractMap = new HashMap();
				
				Result retVal = ValidatorResultHandler.handle(result);
				if("0".equalsIgnoreCase(retVal.getStatus())){
					return retVal;
				}
				
				BigDecimal total_amount=new BigDecimal(0);
				
				//验证套餐总价
				String[] packagestr=new String[application.getPackages().size()] ;
				for(int i=0;i<application.getPackages().size();i++){
	
					Packages packages=application.getPackages().get(i);
					
					packagestr[i]=packages.getId();
					
					total_amount=total_amount.add(new BigDecimal(packages.getReal_price()));
					
				}
				
				System.out.println(total_amount);
				
				for(RequestUser guardian:application.getGuardians()){
					MyTools.checkIsNotNull(guardian.getC_user_id());
					guardian.setC_family_id(application.getC_family_id());
					Map<String,Object> hm3=cardApiService.addUser(guardian,request);
					if(hm3.get(ApplicationUtils.STATUS).equals("0")){
						return hm3;
					}
				}
				
				int effect4=memberCardApiMapper.deleteContractBaby(application.getApplicationID());
				
				for(RequestUser baby:application.getBabies()){
					MyTools.checkIsNotNull(baby.getC_user_id());
					
					baby.setC_family_id(application.getC_family_id());
					baby.setC_role_id("0");
					Map<String,Object> hm3=cardApiService.addUser(baby,request);
					
					if(hm3.get(ApplicationUtils.STATUS).equals("0")){
						return hm3;
					}
					
					Map<String,Object> hm2=new HashMap();
					hm2.put("applicationID", application.getApplicationID());
					hm2.put("InitialOperatorID", application.getInitialOperatorID());
					hm2.put("InitialOperatorName", application.getInitialOperatorName());
					hm2.put("c_user_id", baby.getC_user_id());
					hm2.put("member_name", baby.getMember_name());
					hm2.put("sex_code", baby.getSex_code());
					hm2.put("birthday", baby.getBirthday());
					hm2.put("name", baby.getReal_name());
				
					memberCardApiMapper.insertContractBabys(hm2);
					
				}
				
				int effect=ssoMapper.updateFamily2(application);
				if(effect<1){					
//					m.put(ApplicationUtils.STATUS, "0");
//					m.put(ApplicationUtils.MSG, "");
//					return m;
				}
				//删除旧package
				int effect2=memberCardApiMapper.deleteApplicationsPackages(application.getApplicationID());
				//插入新package
				for(int i=0;i<application.getPackages().size();i++){
					Packages packages=application.getPackages().get(i);												
					HashMap hm7=new HashMap();
					hm7.put("c_membercard_applicationID", application.getApplicationID());
					hm7.put("packageID", packages.getId());
					hm7.put("real_price", packages.getReal_price());
					hm7.put("reason", packages.getReason());
					int effect3=memberCardApiMapper.insertApplicationPackage(hm7);
					if(effect3!=1){
						throw new Exception();
					}
				}	
				
				HashMap hm6=new HashMap();
				hm6.put("package", packagestr);			
				BigDecimal packagePrice=new BigDecimal(0);
						if(packagestr!=null&&packagestr.length>0){
							memberCardApiMapper.getPackagePrice(hm6);
						}
							
				
				application.setOrigin_price(packagePrice);
				application.setAmount(total_amount);				
				
				int effect3=memberCardApiMapper.updateApplication2(application);

				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, "修改成功");
				return m;
		}

		public Map<String, Object> checkParameter(String card_number,String card_out_number){
			
			Map<String, Object> m = new HashMap();
			
			HashMap hm = new HashMap();
			hm.put("card_number", card_number);
			hm.put("card_out_number", card_out_number);
			
			if(card_number!=null){
				int count3= memberCardApiMapper.checkCardNumber(hm);
				if(count3>=1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "该卡已被使用");
					return m;
				}				
			}
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "成功");
			return m;
		}
		
		@Override
		public Map<String, Object> applyCardPayment(String order_payment2,String c_membercard_applicationID,String payment_amount,
				String card_number,String card_out_number,String contract_name,String begin_time,String end_time,String file,
				String OperatorID,String OperatorName,String rechargeAmount,String totalDueAmount,String earnestMoney,String assistant_id,
				String assistant_name,String isDiscount,String kids_park_id,HttpServletRequest request) throws Exception{
			
			Map<String, Object> m = new HashMap();
			
			if(card_number!=null&&card_number.equals("")){
				card_number=null;
			}
			if(card_number!=null&&card_number.equals("null")){
				card_number=null;
			}
			
			if(card_out_number!=null&&card_out_number.equals("")){
				card_out_number=null;
			}
			
			if(card_out_number!=null&&card_out_number.equals("null")){
				card_out_number=null;
			}
			
			
			HashMap hmc=MyTools.checkIsNotNull(c_membercard_applicationID,contract_name,order_payment2);
			if(hmc!=null){
				return hmc;
			}
						
			HashMap hm = new HashMap();
			hm.put("c_membercard_applicationID", c_membercard_applicationID);
			hm.put("card_number", card_number);
			hm.put("card_out_number", card_out_number);
			
			int count2=memberCardApiMapper.checkApplicationID(hm);
			if(count2==0){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "该申请id无效");
				return m;
			}
			
			if(card_number!=null){
				int count3= memberCardApiMapper.checkCardNumber(hm);
				if(count3>=1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "该卡已被使用");
					return m;
				}				
			}			
			
			HashMap ApplicationContent = memberCardApiMapper.getApplicationContent(hm);
						
			String c_user_id=String.valueOf(ApplicationContent.get("c_user_id"));
			String total_amount=String.valueOf(ApplicationContent.get("total_amount"));
			
			//计算充值卡和会员卡之和
			BigDecimal t=new BigDecimal(total_amount);
			if(rechargeAmount!=null&&!rechargeAmount.equals("0")){
				t=new BigDecimal(total_amount).add(new BigDecimal(rechargeAmount));
			}
			
			BigDecimal paid_amount=new BigDecimal(String.valueOf(ApplicationContent.get("paid_amount")));	
		
			SsoUser ssoUser=ssoMapper.getUserByID(c_user_id);
			
			if((!(card_number==null||card_number.equals("")))&&(ssoUser.getCard_number()!=null&&!ssoUser.getCard_number().equals(""))){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "该用户已经绑定了会员卡无需再绑定会员卡");
				return m;
			}
			
			if(ssoUser.getCard_number()==null&&card_number==null){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "该用户还没有绑定会员卡请输入会员卡");
				return m;
			}
		
			//检验实际支付
			if(payment_amount==null){
				payment_amount=total_amount;
			}
			float payment_amountf=Float.valueOf(payment_amount);
			float total_amountf=Float.valueOf(total_amount);
			if(payment_amountf>total_amountf){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "实际支付不能超过总金额");
				return m;
			}
			
			BigDecimal sum_amount=new BigDecimal(0);
			
			JSONArray json = JSONArray.fromObject(order_payment2);
			// 循环添加数据
			for (int i = 0; i < json.size(); i++) {		
				
				JSONObject jsonObject = json.getJSONObject(i);					
				String amount=MyTools.ObjectToString(jsonObject.get("amount"));				
				BigDecimal amountB=new BigDecimal(amount);				
				sum_amount=sum_amount.add(amountB);
				
			}
			sum_amount=sum_amount.add(paid_amount);			
			BigDecimal  payment_amountfb= new BigDecimal(payment_amount);
			
			System.out.println(sum_amount.compareTo(payment_amountfb));
			
			System.out.println(sum_amount);
			System.out.println(payment_amountfb);
			
/*			if(sum_amount.compareTo(payment_amountfb)!=0){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "支付金额不等于各方式支付金额之和");
				return m;
			}*/
			
			
			String kids_parkID=String.valueOf(ApplicationContent.get("kids_parkID"));
			
			hm.put("kids_parkID", kids_parkID);
			
			//产生order_detail
			List<HashMap> order_detail=new ArrayList();
			HashMap order_detailObject=new HashMap();
			order_detailObject.put("business_type_code", 100+"");
			order_detailObject.put("unit_code", 7+"");
			order_detailObject.put("amount", total_amount+"");
			order_detailObject.put("quantity", 1+"");
			
		//	String  order_product_kids_park_ids = memberCardApiMapper.getOrderProduct(hm);
			
			String[] order_product_kids_park_ids = memberCardApiMapper.getOrderProduct(hm);
			if(order_product_kids_park_ids.length<1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "充值卡商品没有被维护，请联系后台维护充值卡商品");
				return m;	
			}
			String order_product_kids_park_id=order_product_kids_park_ids[0];
			
			
		//	String order_product_kids_park_id=String.valueOf(OrderProduct.get("order_product_kids_park_id"));
			
			order_detailObject.put("order_product_kids_park_id", order_product_kids_park_id);
			
			order_detail.add(order_detailObject);
			
			//产生order_payment
			List<HashMap> order_payment=new ArrayList();
	
			BigDecimal useAmount=new BigDecimal("0");
			JSONArray json2 = JSONArray.fromObject(order_payment2);
			// 循环添加数据
			for (int i = 0; i < json.size(); i++) {		
				
				JSONObject jsonObject = json2.getJSONObject(i);			
								
//				String amount=MyTools.ObjectToString(jsonObject.get("amount"));				
//				BigDecimal amountB=new BigDecimal(amount);				
//				sum_amount=sum_amount.add(amountB);		
				
				String rechargecard_id=MyTools.ObjectToString(jsonObject.get("rechargecard_id"));												
				String amount=MyTools.ObjectToString(jsonObject.get("amount"));
				String payment_way_code=MyTools.ObjectToString(jsonObject.get("payment_way_code"));
				
				HashMap hmr=MyTools.checkIsNotNull(amount,payment_way_code);
				if(hmr!=null){
					return hmr;
				}
				
				BigDecimal amountf=new BigDecimal(amount);
				//如果是充值卡 乘以打折率
				if(payment_way_code.equals("2")){
					HashMap<String,Object> hmn=new HashMap<String,Object>();
					hmn.put("rechargecardID", rechargecard_id);
					
					HashMap rechargecard=consumeBackgroundMapper.getRechargecardDetailByCardNumber(hmn);
					
					//BigDecimal a1=(BigDecimal)rechargecard.get("balance");
					BigDecimal discount_rate=(BigDecimal)rechargecard.get("discount_rate");
					 
					if(isDiscount.equals("1")){
						amountf=discount_rate.multiply(new BigDecimal(amount));
					} 
					 useAmount=useAmount.add(amountf);
				}
			
				HashMap order_paymentObject=new HashMap();
				
				order_paymentObject.put("payment_way_code", payment_way_code);
				order_paymentObject.put("amount", amount);
				order_paymentObject.put("totalAmount", amountf.toString());
				order_paymentObject.put("rechargecard_id", rechargecard_id);
												
				order_payment.add(order_paymentObject);
	
			}
			
			//订金部分
/*			if(paid_amount.compareTo(new BigDecimal(0))!=0){
				HashMap order_paymentObject=new HashMap();
				
				order_paymentObject.put("payment_way_code", "3");
				order_paymentObject.put("amount", paid_amount);
				order_paymentObject.put("totalAmount", paid_amount);												
				order_payment.add(order_paymentObject);
			}*/
			
			System.out.println(order_payment.toString());
			
			JSONArray order_paymentJson = JSONArray.fromObject(order_payment);
			System.out.println(order_paymentJson.toString());
			
			//产生订单
			Map<String, Object> checkOutReturn=consumeBackgroundService.checkOut(assistant_id,assistant_name,null,c_user_id,null, kids_parkID, t.toString(), payment_amount, "购买会员卡",null, order_detail.toString(), order_paymentJson.toString(),0,null,null,null,null);
			
				
			//得到反馈
			String costatus=String.valueOf(checkOutReturn.get(ApplicationUtils.STATUS)); 
			String comsg= String.valueOf(checkOutReturn.get(ApplicationUtils.MSG));
			String codataset= String.valueOf(checkOutReturn.get(ApplicationUtils.DATASET));
			
			
			if(costatus.equals("0")){
				return checkOutReturn;
			}
			
			Map<String, Object> datasetr=(Map<String, Object>)checkOutReturn.get(ApplicationUtils.DATASET);
			
			String orderID= MyTools.ObjectToString(datasetr.get("orderID"));						
			
			
			
			String real_name=ssoUser.getReal_name();//  ssoMapper.selectRealNameByID(c_user_id);
			
			//得到各个必要的参数
			HashMap afterPayPara=ApplicationContent;
			afterPayPara.put("order_product_kids_park_id", order_product_kids_park_id);
			
			
			//如果已经有会员卡了卡号用旧的卡号
			if(card_number==null){
				card_number=ssoUser.getCard_number();
				card_out_number=ssoUser.getCard_out_number();	
			}			
			
			afterPayPara.put("orderID", orderID);
			afterPayPara.put("card_number", card_number);
			afterPayPara.put("card_out_number", card_out_number);
			afterPayPara.put("user_name", real_name);
			
			
			HashMap KidsAndRegion=memberCardApiMapper.getKidsAndRegion(afterPayPara);
			String index=String.valueOf(KidsAndRegion.get("index"));
			String areaCode=String.valueOf(KidsAndRegion.get("areaCode"));
			
			afterPayPara.put("index", index);
			afterPayPara.put("areaCode", areaCode);
			
//			HashMap PackageID=memberCardApiMapper.getPackageID(afterPayPara);
//			String packageID=String.valueOf(PackageID.get("packageID"));
//			afterPayPara.put("packageID", packageID);
			
			
			
			//生成会员号
			//得到注册数
			String count=memberCardApiMapper.getMemberCount(afterPayPara);			
			if(index.length()==1){
				index="0"+index;
			};			
			
			Date d=new Date();
			SimpleDateFormat sFormat = new SimpleDateFormat("yy");
			String year=sFormat.format(d);
			
			String member_number=areaCode+index+"1"+year+count;
			
			

			HashMap<String ,Object> hm2=new HashMap<String ,Object>();
			hm2.put("c_user_id", c_user_id);
			hm2.put("kid_park_id", kids_parkID);
			hm2.put("phone", ssoUser.getPhone());
			//hm2.put("kid_park_id", kids_parkID);
			
			String MemberNumber=ssoUser.getMember_number();//  ssoMapper.getMemberByID(hm2);
			
			//修改用户表  成为会员
			if(MemberNumber==null||MemberNumber.equals("")||!"2".equalsIgnoreCase(ssoUser.getMember_type())){
				String count4=memberCardApiMapper.getDistinctMemberCount(kids_parkID);
				
				String sso_member_number=areaCode+index+year+count4;
				
				hm2.put("member_number", sso_member_number);
				hm2.put("card_number", card_number);
				hm2.put("card_out_number", card_out_number);
				hm2.put("member_type", "2");
				int effect=ssoMapper.updateUserNumber(hm2);
					
				if(effect<1){
					throw new Exception();
				}
				int effect2= ssoMapper.updateUserFamilyNumber(hm2);
				if(effect2<1){
					throw new Exception();
				}
			}
		
//			System.out.println("member_number"+member_number);
			
			afterPayPara.put("member_number", member_number);
			
			String membercardID=ApplicationUtils.randomUUID();
			afterPayPara.put("membercardID", membercardID);
			afterPayPara.put("contract_name", contract_name);
			afterPayPara.put("begin_time", begin_time);
			afterPayPara.put("end_time", end_time);
			
			afterPayPara.put("InitialOperatorID", OperatorID);
			afterPayPara.put("InitialOperatorName", OperatorName);
			afterPayPara.put("OperatorID", OperatorID);
			afterPayPara.put("OperatorName", OperatorName);
			
			String crmCustomerID=commonApiMapper.getCrmCustomerID(c_user_id);
			CrmCustomer cc=new CrmCustomer();
			cc.setId(crmCustomerID);
			cc.setServicestage(2);		
			crmCustomerMapper.updateByPrimaryKeySelective(cc);
			
			String contractStatus="1";
			
			if(paid_amount.compareTo(new BigDecimal("0"))==0){
				contractStatus="2";
			}
			
			//插入合同
			HashMap ic=afterPayPara;
			ic.put("contractTypeCode", 1);
			ic.put("contractNumber", member_number);
			ic.put("name", contract_name);
			ic.put("desc", "");
			ic.put("beginTime", begin_time);
			ic.put("endTime", end_time);
			ic.put("InitialOperatorID", OperatorID);
			ic.put("InitialOperatorName", OperatorName);
			ic.put("partA", real_name);
			ic.put("kids_parkID", kids_parkID);
			ic.put("crmCustomerID", crmCustomerID);
			ic.put("phone", ssoUser.getPhone());
			ic.put("amount", t);
			ic.put("earnestAmount", paid_amount);
			ic.put("contractStatus", contractStatus);
			ic.put("totalDueAmount", totalDueAmount);
			ic.put("totalDueAmount", totalDueAmount);
			
			Map<String, Object> r= cardApiService.insertContract(ic);
			r.get(ApplicationUtils.STATUS);
			if(r.get(ApplicationUtils.STATUS).equals("0")){
				throw new Exception();
			}
			
			//HashMap<String, Object> rd = (HashMap<String, Object>)r.get("dataset");
			//String contractID=(String)rd.get("contractID");
			

			

			HashMap hm5=(HashMap)r.get(ApplicationUtils.DATASET);
			//合同id
			String contractID=String.valueOf(hm5.get("contractID"));
			
			afterPayPara.put("contractID", contractID);		
			
			TracelogboWithBLOBs traclelogba = MyTools.getOaLogByRequest(request);
			traclelogba.setEntitytypename("contract");
			traclelogba.setEntityid(contractID);
			traclelogba.setLogcategory(1);
			traclelogba.setLogdescription(MyTools.getChangeByMap(ic, "新增"));
			int effect=tracelogboMapper.insert(traclelogba);
			System.out.println(effect);
			
			
			if(file!=null&&!file.equals("")){
				Map<String, Object> cm=cardApiService.insertFile(file, contractID);
			}
			
			//if(paid_amount.toString().equals("0")){
			if(paid_amount.compareTo(new BigDecimal("0"))==0){
				afterPayPara.put("EntityAvailableState", 10);
			}else{
				afterPayPara.put("EntityAvailableState", 2);	
			}			
						
			//插入会员卡表
			int effect2=memberCardApiMapper.insertMembercard(afterPayPara);
			if(effect2==0){
				throw new Exception();
			}
			//插入关联表
			int effect5=memberCardApiMapper.insertContractPackage(afterPayPara);
			if(effect5==0){
			//	throw new Exception();
			}			
			
			//插入会员卡详细报
			int effect3=memberCardApiMapper.insertCardDetail(afterPayPara);
			if(effect3==0){
			//	throw new Exception();
			}
			
			int effect4=memberCardApiMapper.updateApplicationAfterPay(afterPayPara);
			
			if(effect4==0){
			//	throw new Exception();
			}
			
			String point=String.valueOf(ApplicationContent.get("point"));
			
			Map<String, Object> updatePointmap= cardApiService.updatePoint(c_user_id, "2", point, "1", "购买会员卡");
			String updatePointmapStatus=String.valueOf(updatePointmap.get(ApplicationUtils.STATUS));
			if(updatePointmapStatus.equals("0")){
			//	return updatePointmap;
			}
			
			System.out.println(updatePointmap.toString());
			
			//String coupon_code=String.valueOf(ApplicationContent.get("coupon_code"));
			
			//修改老会员积分
			HashMap coupon=memberCardApiMapper.getCoupon(ApplicationContent);
			if(coupon!=null){
				if(!coupon.equals("")){
			String user_id=String.valueOf(coupon.get("user_id"));
			String gpoint=String.valueOf(coupon.get("point"));
			Map<String, Object> updateOldPointmap= cardApiService.updatePoint(user_id, "1", gpoint, "1", "老会员介绍新会员");
			String updateOldPointmapStatus=String.valueOf(updateOldPointmap.get(ApplicationUtils.STATUS));
			if(updateOldPointmapStatus.equals("0")){
			//	return updateOldPointmap;
			}
			
			}
			}			
			
			//更新合同孩子关联表
			UpdateMap up = new UpdateMap("contract_baby");
			up.addField("contractID", contractID);
			up.addWhere("applicationID", c_membercard_applicationID);
			commonMapper.update(up);
			
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "插入成功");
			m.put("contractID", contractID);
			m.put("orderID", orderID);
			m.put("useAmount", ((HashMap<String,Object>)checkOutReturn.get("dataset")).get("useAmount"));
			
			//checkOutReturn.get("useAmount");
			
			return m;
		}
		
		@Override
		public BaseResult applyCardPaymentRemain(int isPaidAll,String order_payment2,String contractID,String isDiscount) throws Exception{
			//产生order_payment
			List<HashMap> order_payment=new ArrayList();

			JSONArray json2 = JSONArray.fromObject(order_payment2);
			// 循环添加数据
			for (int i = 0; i < json2.size(); i++) {		
				
				JSONObject jsonObject = json2.getJSONObject(i);							
				String rechargecard_id=MyTools.ObjectToString(jsonObject.get("rechargecard_id"));												
				String amount=MyTools.ObjectToString(jsonObject.get("amount"));
				String payment_way_code=MyTools.ObjectToString(jsonObject.get("payment_way_code"));
				
				HashMap hmr=MyTools.checkIsNotNull(amount,payment_way_code);
				if(hmr!=null){
					return new BaseResult("0","请输入必要参数");
				}
				
				BigDecimal amountf=new BigDecimal(amount);
				//如果是充值卡 乘以打折率
				if(payment_way_code.equals("2")){
					HashMap<String,Object> hmn=new HashMap<String,Object>();
					hmn.put("rechargecardID", rechargecard_id);
					
					HashMap rechargecard=consumeBackgroundMapper.getRechargecardDetailByCardNumber(hmn);
					
					//BigDecimal a1=(BigDecimal)rechargecard.get("balance");
					BigDecimal discount_rate=(BigDecimal)rechargecard.get("discount_rate");
					if(isDiscount.equals("1")){
					 amountf=discount_rate.multiply(new BigDecimal(amount));
					 }else{
						 amountf=new BigDecimal(amount);
					 }
				}
			
				HashMap order_paymentObject=new HashMap();
				
				order_paymentObject.put("payment_way_code", payment_way_code);
				order_paymentObject.put("amount", amount);
				order_paymentObject.put("totalAmount", amountf.toString());
				order_paymentObject.put("rechargecard_id", rechargecard_id);
												
				order_payment.add(order_paymentObject);	
			}
				
				JSONArray order_paymentJson = JSONArray.fromObject(order_payment);
				System.out.println(order_paymentJson.toString());
				
				String orderID = memberCardApiMapper.getOrderIDByContractID(contractID);
				
				//产生订单
				Map<String, Object> checkOutReturn=consumeBackgroundService.checkOut(null,null,orderID,null,null, null, null, null, null,null, null, order_paymentJson.toString(),0,null,null,null,null);
				String status=(String)checkOutReturn.get("status");
				String msg=(String)checkOutReturn.get("msg");
				Map<String,Object> dataset=(HashMap<String,Object>)checkOutReturn.get("dataset");
				if(status.equals("0")){
					return new BaseResult("0",msg);
				}
			
				int EntityAvailableState=10;
				if(isPaidAll!=1){			
					EntityAvailableState=2;
				}
				Map<String,Object> datasets=new HashMap<String,Object>();
				datasets.put("EntityAvailableState", EntityAvailableState);
				datasets.put("useAmount",dataset.get("useAmount"));
				datasets.put("contractID", contractID);
								
			if(isPaidAll==1){
				int effect=memberCardApiMapper.updatePaymentStatus(contractID);
				if(effect>0){
					return new BaseResult("1","操作成功",datasets);
				}else{
					return new BaseResult("0","操作失败");
				}
			}	

			return new BaseResult("1","操作成功",datasets);
		}
		
		
		

		@Override
		public Map<String, Object> getFamilyDetail(String phone,String card_number,String member_number) throws Exception {
			Map<String, Object> m = new HashMap();
			
			if((phone==null||phone.equals(""))&&(card_number==null||card_number.equals(""))&&(member_number==null||member_number.equals(""))){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入查询条件");
				return m;
			}
			
			
			HashMap hm=new HashMap();
			hm.put("phone", phone);
			hm.put("card_number", card_number);
			hm.put("member_number", member_number);
						
			List<SsoFamily> list = ssoMapper.getFamilyDetailByPhone(hm);
			//如果主签约人phone为空返回参数中的phone
			for(SsoFamily sf:list){
				if(sf.getPhone()==null&&phone!=null&&!phone.equals("")){
					sf.setPhone(phone);
				}
			}
			
			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");

			return m;
		}
		
		@Override
		public Map<String, Object> getContractByID(String contractID) throws Exception {
			
			Map<String, Object> m = new HashMap();
			HashMap hm=new HashMap();
			hm.put("contractID", contractID);
			
			BigDecimal totalBalance=rechargeApiMapper.getTotalRechargeAmount(contractID);
			
			Map<String, Object> dataset = new HashMap();
			
			List<ApplicationB> membercard = memberCardApiMapper.getApplicationByID(hm);
			
			if(membercard.size()>0){
				//计算折扣金额
				ApplicationB ab=membercard.get(0);
				
				dataset.put("contract", ab.getContract());
				ab.getContract().setTotalBalance(totalBalance);	

				String phone=ab.getContract().getPhone();
				
				ab.setContract(null);
				
				//String phone=ab.getPhone();
				Map<String, Object> ssoFamilym=this.getFamilyDetail(phone, null, null);
				List<SsoFamily> ssoFamily=(List<SsoFamily>)ssoFamilym.get(ApplicationUtils.DATASET);
				
				dataset.put("ssoFamily", ssoFamily);			
			}
			
			dataset.put("membercard", membercard);

			List<com.spring.rechargeapi.web.model.ApplicationB> rechargeCard = rechargeApiMapper.getApplicationByID(hm);
			
			if(rechargeCard.size()>0){
				com.spring.rechargeapi.web.model.ApplicationB application=rechargeCard.get(0);
				
				String phone=MyTools.ObjectToString(application.getPhone());
				Map<String, Object> ssoFamilym=this.getFamilyDetail(phone, null, null);
/*				List<SsoFamily> ssoFamily=(List<SsoFamily>)ssoFamilym.get(ApplicationUtils.DATASET);
				
				dataset.put("ssoFamily", ssoFamily);*/
				if(membercard.size()==0){		
					BigDecimal realAmount=rechargeApiMapper.getRechargeContractAmount(contractID);
					
					System.out.println(realAmount);
					
					com.spring.membercardapi.web.model.Contract contract=application.getContract();
					contract.setRealAmount(realAmount);
					contract.setTotalBalance(totalBalance);					
					dataset.put("contract", contract);
				}				
				application.setContract(null);
			}			
			dataset.put("rechargecard", rechargeCard);

			m.put(ApplicationUtils.DATASET, dataset);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");
			
			return m;
		}
		
		@Override
		public Map<String, Object> getApplicationByID(String application_id) throws Exception {
			Map<String, Object> m = new HashMap();
			HashMap hm=new HashMap();
			hm.put("applicationID", application_id);

			List<ApplicationB> list = memberCardApiMapper.getApplicationByID(hm);
			
			if(list.size()>0){
				//计算折扣金额
				ApplicationB ab=list.get(0);
				
				/*				BigDecimal amount=ab.getAmount();
				BigDecimal discount_amount=ab.getDiscount_amount();
				
				BigDecimal card_discount_amount= amount.subtract(discount_amount);
				
				List<OrderPayment> ops=ab.getContract().getOrder_payment();
				for(OrderPayment op:ops){
					card_discount_amount=card_discount_amount.subtract(op.getAmount());									
				}
				
				ab.setCard_discount_amount(card_discount_amount);
				
				for(OrderPayment op:ops){
					if(op.getPayment_way_code().equals("2")){
						op.setTotal_amount(card_discount_amount.add(op.getAmount()));
					}								
				}*/
					
				String phone=ab.getPhone();
				Map<String, Object> ssoFamilym=this.getFamilyDetail(phone, null, null);
				List<SsoFamily> ssoFamily=(List<SsoFamily>)ssoFamilym.get(ApplicationUtils.DATASET);
				
				ab.setSsoFamily(ssoFamily);				
			}			

			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");

			return m;
		}
		
		
		
		@Override
		public Map<String, Object> checkCoupon(String phone,String c_user_id,String coupon_code) throws Exception {
			Map<String, Object> m = new HashMap();
			HashMap hm=new HashMap();
			hm.put("phone", phone);
			
			if(c_user_id==null){
				c_user_id=ssoMapper.getIDByPhone(hm);
			}
			
			hm.put("c_user_id", c_user_id);
			hm.put("coupon_code", coupon_code);
						
			
			List<HashMap<String, Object>> list = memberCardApiMapper.checkCoupon(hm);
			
			if(list.size()<1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "优惠码无效");
				return m;
			}
			
			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");

			return m;
		}
		
		@Override
		public BaseResult updateContract(ContractUpdate contractUpdate,HttpServletRequest request) throws Exception{

		Contract contract = contractUpdate.getContract();

		this.updateFamily(contractUpdate.getSsoFamily(), contract,request);
		if (contractUpdate.getMembercard() != null) {
			this.updateMembercard(contract, contractUpdate.getMembercard(),request);
		}
		if (contractUpdate.getRechargecard() != null) {
			this.updateRechargecard(contract, contractUpdate.getRechargecard(),request);
		}
		BaseResult ret=this.updateOrder(contract, contractUpdate.getMembercard(),contractUpdate.getIsDiscount());
		this.updateContracts(contract);

		BigDecimal earnestamount=contractUpdate.getContract().getEarnestamount();				
		int EntityAvailableState=10;
		if(earnestamount!=null&&!earnestamount.equals("0")){			
			EntityAvailableState=2;
		}
		Map<String,Object> datasets=new HashMap<String,Object>();
		datasets.put("EntityAvailableState", EntityAvailableState);
		datasets.put("useAmount", ((HashMap<String,Object>)ret.getDataset()).get("useAmount"));
		datasets.put("contractID", contractUpdate.getContract().getId())
		;
		
		return new BaseResult("1","成功",datasets);	 
		} 
		
		public BaseResult updateContracts(Contract contract) throws Exception{
			contractsMapper.updateByPrimaryKeySelective(contract);

			Map<String, Object> cm=cardApiService.insertFile(contract.getFile(), contract.getId());

			return null;
		} 
		
		public BaseResult updateOrder(Contract contract,MembercardApplication membercardApplication,String isDiscount) throws Exception{
			
			MembercardApplication membercardApplicationD=membercardApplicationMapper.selectByPrimaryKey(membercardApplication.getId());
			String payment;
			if(isDiscount.equals("1")){
				payment=convertPaymentToAfterDiscount(contract.getPaymentDetail());
			}else{
				payment=contract.getPaymentDetail();
			}
			Map<String, Object> ret=consumeBackgroundService.checkOut(null, null, membercardApplicationD.getOrderid(),
					null, null, null,null, null, null, null, null, payment, 
					0, null, null, null, null);

			return MyTools.MapToBaseResult(ret);			
		};
		
		public BaseResult updateRechargecard(Contract contract,RechargecardApplication rechargecardApplication,
				HttpServletRequest request) throws Exception{
			
			rechargecardApplication.setData(contract);			
			RechargecardApplication rechargecardApplicationo=rechargecardApplicationMapper.selectByPrimaryKey(rechargecardApplication.getId()) ;			
			rechargecardApplicationo.getUserGetAmount();
			BigDecimal addAmount=rechargecardApplication.getUserGetAmount().subtract(rechargecardApplicationo.getUserGetAmount());
			
			rechargecardApplicationMapper.updateByPrimaryKeySelective(rechargecardApplication);
			
			Rechargecard rechargecard=rechargecardMapper.selectByPrimaryKey(rechargecardApplication.getRechargecardID());			
			rechargecard.setBalance(rechargecard.getBalance().add(addAmount));			
			rechargecard.setData(rechargecardApplication, contract);
			
			rechargecardMapper.updateByPrimaryKeySelective(rechargecard);
			
			TracelogboWithBLOBs tl = MyTools.getOaLogByRequest(request);
			tl.setEntitytypename("rechargecard");
			tl.setEntityid(rechargecardApplication.getRechargecardID());
			tl.setLogcategory(2);
			tl.setLogdescription(MyTools.getChangeByObject(rechargecard, "修改"));
			int effect=tracelogboMapper.insert(tl);
			System.out.println(effect);	
			
			return null;
		}
		
		public BaseResult updateMembercard(Contract contract,MembercardApplication membercardApplication,HttpServletRequest request) throws Exception{
			membercardApplication.setData(contract);
			
			membercardApplicationMapper.updateByPrimaryKeySelective(membercardApplication);
			
			List<MembercardApplicationsPackages> MembercardApplicationsPackages = membercardApplication.getPackages();
			
			if(MembercardApplicationsPackages!=null){
				for(MembercardApplicationsPackages membercardApplicationsPackage:MembercardApplicationsPackages){				
					membercardApplicationsPackage.setcMembercardApplicationid(membercardApplication.getId());
					membercardApplicationsPackagesMapper.insert(membercardApplicationsPackage);		
					
					String packageID=membercardApplicationsPackage.getPackageid();	
				}
			}			
			//修改card_detail
			HashMap<String,Object> param=new HashMap<String,Object>();
			param.put("c_membercard_applicationID", membercardApplication.getId());
			param.put("membercardID", membercardApplication.getMembercardID());			
			memberCardApiMapper.insertCardDetail(param);
			
			Membercard membercard=new Membercard();
			membercard.setData(membercardApplication, contract);
			
			membercardMapper.updateByPrimaryKeySelective(membercard);
			
			TracelogboWithBLOBs tl = MyTools.getOaLogByRequest(request);
			tl.setEntitytypename("membercard");
			tl.setEntityid(membercardApplication.getMembercardID());
			tl.setLogcategory(2);
			tl.setLogdescription(MyTools.getChangeByObject(membercard, "修改"));
			int effect=tracelogboMapper.insert(tl);
			System.out.println(effect);	
			
			return null;
		}
		
		
		public BaseResult updateFamily(SsoFamily ssoFamily,Contract contract,HttpServletRequest request) throws Exception{

			familyMapper.updateByPrimaryKeySelective(ssoFamily);
			
			List<RequestUser> ssoFamilyUsers=ssoFamily.getFamilyMember();
			
			for(RequestUser requestUser:ssoFamilyUsers){				
				String newUserid=requestUser.getC_user_id();
				requestUser.setC_family_id(ssoFamily.getC_family_id());
				Map<String,Object> rt=cardApiService.addUser(requestUser,request);	

				if(requestUser.getC_role_id().equals("0")){
					if(requestUser.getIsToDelete()==1){		
						
						ContractBaby param=new ContractBaby();
						param.setContractid(contract.getId());
						param.setCuserid(requestUser.getC_user_id());
						contractBabyMapper.deleteByCondition(param);
					}
					else if(newUserid==null){
						String newBabyID=(String)((Map<String,Object>)rt.get("dataset")).get("c_user_id");
						
						requestUser.setC_user_id(newBabyID);
						ContractBaby contractBaby=new ContractBaby();
						contractBaby.setData(contract, requestUser);
						
						contractBabyMapper.insert(contractBaby);
					}
					
				}
			}			
			return new BaseResult("1","成功");
		}
		
		public String convertPaymentToAfterDiscount(String orderPayment){
		//产生order_payment
			JSONArray orderPaymentJsonArray = JSONArray.fromObject(orderPayment);
			// 循环添加数据
			for (int i = 0; i < orderPaymentJsonArray.size(); i++) {					
				JSONObject paymentDetailJsonObject = orderPaymentJsonArray.getJSONObject(i);					
				String paymentWayCode=MyTools.ObjectToString(paymentDetailJsonObject.get("payment_way_code"));
				
				if(paymentWayCode.equals("2")){
					String rechargecardID=MyTools.ObjectToString(paymentDetailJsonObject.get("rechargecard_id"));												
					String amount=MyTools.ObjectToString(paymentDetailJsonObject.get("amount"));
					
					HashMap<String,Object> param=new HashMap<String,Object>();
					param.put("rechargecardID", rechargecardID);
					HashMap<String,Object> rechargecardHM=consumeBackgroundMapper.getRechargecardDetailByCardNumber(param);
					BigDecimal discountRate=(BigDecimal)rechargecardHM.get("discount_rate");
					BigDecimal AfterDiscountAmount=discountRate.multiply(new BigDecimal(amount));
					
					paymentDetailJsonObject.put("amount", AfterDiscountAmount);					
				}
			 }
			 return orderPaymentJsonArray.toString();
		}
		

}
